<template>
  <div class='container'>
    <el-card>
      <!-- 筛选区域 -->
      <!-- 按钮组件 -->
      <el-row
        type="flex"
        justify="end"
        style="margin-bottom:15px"
      >
        <el-button
          size="small"
          type="success"
          icon="el-icon-edit"
          @click="$router.push('/questions/new')"
        >新增试题</el-button>
      </el-row>
      <!-- 下拉菜单区域 -->
      <el-form label-width="80px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="学科">
              <el-select
                @focus="getSubjectList"
                v-model="formData.subjectID"
                clearable
                style="width:100%"
              >
                <el-option
                  v-for="item in subjectList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="试题类型">
              <el-select
                v-model="formData.questionType"
                clearable
                style="width:100%"
              >
                <el-option
                  v-for="item in questionList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="题目备注">
              <el-input
                placeholder="请输入"
                v-model="formData.remarks"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="二级目录">
              <el-select
                v-model="formData.catalogID"
                clearable
                @focus="getCatalogList"
                style="width:100%"
              >
                <!-- 这个目录的接口返回的数据有问题，逻辑应该是对的 -->
                <el-option
                  v-for="item in catalogList"
                  :key="item.id"
                  :label="item.directoryName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="难度">
              <el-select
                v-model="formData.difficulty"
                clearable
                style="width:100%"
              >
                <el-option
                  v-for="item in difficultyList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业简称">
              <el-input
                placeholder="请输入"
                v-model="formData.shortName"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标签">
              <el-select
                @focus="getTagsList"
                v-model="formData.tags"
                clearable
                style="width:100%"
              >
                <el-option
                  v-for="item in tagsList"
                  :key="item.id"
                  :label="item.tagName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="方向">
              <el-select
                v-model="formData.direction"
                clearable
                style="width:100%"
              >
                <el-option
                  v-for="item in directionList"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="城市">
              <el-select
                @focus="getProvinces"
                v-model="formData.province"
                clearable
                style="width:49%"
              >
                <el-option
                  v-for="item in provinces"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
              <el-select
                v-model="formData.city"
                clearable
                @focus="getCitys"
                style="width:49%;margin-left:2%"
              >
                <el-option
                  v-for="area in citys"
                  :key="area"
                  :label="area"
                  :value="area"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关键字">
              <el-input
                placeholder="请输入"
                v-model="formData.keyword"
              />
            </el-form-item>
            <el-form-item label="录入人">
              <el-select
                @focus="getCreatorList"
                v-model="formData.creatorID"
                clearable
                style="width:100%"
              >
                <el-option
                  v-for="item in creatorList"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-row
              type="flex"
              justify="end"
            >
              <el-button
                size="mini"
                @click="reset"
              >清除</el-button>
              <el-button
                size="mini"
                type="primary"
                @click="search"
              >搜索</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>

      <!-- 列表区域 -->
      <!-- tabs标签页 -->
      <el-tabs
        type="card"
        v-model="chkState"
        @tab-click="handleClick"
      >
        <!-- 0 全部； 1 待审核； 2 已审核； 3 已拒绝 -->
        <el-tab-pane
          label="全部"
          name="0"
        ></el-tab-pane>
        <el-tab-pane
          label="待审核"
          name="1"
        ></el-tab-pane>
        <el-tab-pane
          label="已审核"
          name="2"
        ></el-tab-pane>
        <el-tab-pane
          label="已拒绝"
          name="3"
        ></el-tab-pane>
      </el-tabs>

      <!-- alert 提示信息 -->
      <el-alert
        :title="`数据一共 ${counts} 条`"
        type="info"
        show-icon
        :closable="false"
        style="margin-bottom:15px"
      />

      <!-- 列表区域 -->
      <el-table
        :data="tableData"
        :row-style="{height: '60px'}"
        empty-text='暂无数据'
      >
        <el-table-column
          label="试题编号"
          prop="number"
          width="120"
        />
        <el-table-column
          label="学科"
          prop="subjectID"
          width="120"
        >
          <template v-slot="{row}">
            <span>{{ getSubject(row.subjectID) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="目录"
          prop="catalogID"
          width="120"
        >
          <template v-slot="{row}">
            <!-- 给计算属性传递参数  -->
            <span>{{ getCatalog(row.catalogID) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="题型"
          prop="questionType"
          width="120"
        >
          <template v-slot="{row}">
            <span>{{ getQuestion(row.questionType)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="题干"
          prop="question"
          width="300"
        >
          <template v-slot="{row}">
            <span class="ellipsisStyle">{{row.question}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="录入时间"
          prop="addDate"
          width="180"
        >
          <template v-slot="{row}">
            <span>{{row.addDate | parseTimeByString }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="难度"
          prop="difficulty"
          width="120"
        >
          <template v-slot="{row}">
            <span>{{ getDifficulty(row.difficulty) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="录入人"
          prop="creator"
          width="120"
        />
        <el-table-column
          label="审核状态"
          prop="chkState"
          width="120"
        >
          <template v-slot="{row}">
            <span>{{ getChkState(row.chkState) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="审核意见"
          prop="chkRemarks"
          width="120"
        />
        <el-table-column
          label="审核人"
          prop="chkUser"
          width="120"
        />
        <el-table-column
          label="发布状态"
          prop="publishState"
          width="120"
        >
          <template v-slot="{row}">
            <span>{{ getPublishType(row.publishState) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          prop="number"
          width="200"
        >
          <template v-slot="{row}">
            <el-button
              type="text"
              size="mini"
              @click="preview(row)"
            >预览</el-button>
            <el-button
              type="text"
              size="mini"
              @click="check(row)"
              :disabled="row.chkState===1"
            >审核</el-button>
            <!-- @click="$router.push({
                name:'questions-new',
                params:{data:row}
              })" -->
            <el-button
              type="text"
              size="mini"
              @click="$router.push({
                name:'questions-new',
                params:{id:row.id}
              })"
            >修改</el-button>
            <el-button
              type="text"
              size="mini"
              @click="publish(row)"
            >{{row.publishState===2?'下架':'上架'}}</el-button>
            <el-button
              type="text"
              size="mini"
              @click="remove(row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-row
        type="flex"
        justify="end"
        style="margin-top:25px"
      >
        <el-pagination
          layout="prev,pager,next,sizes,jumper"
          :total="counts"
          :page-sizes="[2,4,6,10]"
          :page-size.sync="formData.pagesize"
          :current-page.sync="formData.page"
          background
          @current-change="CurrentChange"
          @size-change="SizeChange"
        />
      </el-row>

      <!--  题目预览弹出层1  -->
      <el-dialog
        title='题目预览'
        :visible.sync="showDialogPreview"
      >
        <el-form>
          <!-- 基本信息 -->
          <el-row>
            <el-col :span="6">
              <el-form-item label="【题型】:">
                <span>{{getQuestion(dialogData.questionType)}}</span>
              </el-form-item>
              <el-form-item label="【学科】:">
                <span>{{getSubject(dialogData.subjectID)}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="【编号】:">
                <span>{{dialogData.id}}</span>
              </el-form-item>
              <el-form-item label="【目录】:">
                <span>{{getCatalog(dialogData.catalogID)}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="【难度】:">
                <span>{{getDifficulty(dialogData.difficulty)}}</span>
              </el-form-item>
              <el-form-item label="【方向】:">
                <span>{{dialogData.direction}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="【标签】:">
                <span>{{dialogData.tags}}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <hr>
          <!-- 题干 12 -->
          <el-form-item label="【题干】:">
            <br>
            <span>{{dialogData.question}}</span>
          </el-form-item>
          <!-- 单选题 -->
          <template v-if="dialogData.questionType==1">
            <div style="line-height:30px">
              {{getQuestion(dialogData.questionType)}}选项：（以下选中的选项为正确选项）</div>
            <el-radio
              v-for="item in dialogData.options"
              :key="item.id"
              :value="right"
              :label="item.isRight"
              style="display:block;line-height:30px"
            >
              {{item.title}}
            </el-radio>
          </template>

          <!-- 多选题 -->
          <template v-if="dialogData.questionType==2">
            <div style="line-height:30px">
              {{getQuestion(dialogData.questionType)}}选项：（以下选中的选项为正确选项）</div>
            <el-checkbox-group :value="multipleRight">
              <el-checkbox
                v-for="item in dialogData.options"
                :key="item.id"
                :label="item.isRight"
                style="display:block;line-height:30px"
              >{{item.title}}</el-checkbox>
            </el-checkbox-group>
          </template>
          <hr>
          <!-- 参考答案 -->
          <el-form-item label="【参考答案】:">
            <el-button
              type="danger"
              size="small"
              @click="isShowVideo=!isShowVideo"
            >{{isShowVideo?"视频答案预览":"关闭视频预览"}}</el-button>
            <div :class="{showVideo:isShowVideo}">
              <video
                :src="dialogData.videoURL"
                width='300'
                height='200'
                loop="loop"
                controls
              ></video>
            </div>
          </el-form-item>
          <hr>
          <!-- 答案解析 -->
          <el-form-item label="【答案解析】:">
            <span>{{dialogData.answer}}</span>
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="【题目备注】:">
            <span>{{dialogData.remarks}}</span>
          </el-form-item>
        </el-form>

        <!-- 关闭按钮 -->
        <template v-slot:footer>
          <el-row
            type="flex"
            justify="end"
          >
            <el-button
              type="primary"
              @click="showDialogPreview=false"
            >关闭</el-button>
          </el-row>
        </template>
      </el-dialog>

      <!-- 显示题目审核 -->
      <el-dialog
        title="题目审核"
        :visible.sync="showDialogCheck"
        @close="CheckBtnCancel"
      >
        <el-radio-group v-model="chkState">
          <el-radio label="2">通过</el-radio>
          <el-radio label="3">拒绝</el-radio>
        </el-radio-group>
        <el-input
          v-model="chkRemarks"
          type="textarea"
          placeholder="请输入审核意见"
          style="margin-top:15px"
        />
        <el-row
          slot="footer"
          type="flex"
          justify="end"
        >
          <el-button
            size="small"
            @click="CheckBtnCancel"
          >取消</el-button>
          <el-button
            size="small"
            type="primary"
            @click="CheckBtnOk"
          >确认</el-button>
        </el-row>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// 引入接口
// 学科简单列表
import { simple as subjectList } from '@/api/hmmm/subjects'
// 目录列表
import { list as catalogList } from '@/api/hmmm/directorys'
// 标签列表
import { list as tagsList } from '@/api/hmmm/tags'
// 通用常量
import { difficulty as difficultyList, questionType as questionList, direction as directionList, chkType as chkStateList, publishType as publishTypeList } from '@/api/hmmm/constants'
// 城市
import { provinces, citys } from '@/api/hmmm/citys'
// 用户列表 -- 获取录入人列表
import { simple as creatorList } from '@/api/base/users'
// 获取精选题库列表、获取题目详情、试题审核提交、试题上下架
import { choice as getChoiceList, detail, choiceCheck, choicePublish, remove } from '@/api/hmmm/questions'

// let that
export default {
  data () {
    return {
      id: '', // 编号
      counts: 0, // 总记录数
      pages: 0, // 总页数
      // 列表
      formData: {
        page: 1, // 当前页码
        pagesize: 2, // 页大小
        subjectID: '', // 学科
        difficulty: '', // 难度
        questionType: '', // 试题类型
        tags: '', // 标签名称
        province: '', // 城市
        city: '', // 区域
        keyword: '', // 关键字
        remarks: '', // 题目备注
        shortName: '', // 企业简称
        direction: '', // 方向
        creatorID: '', // 录入人
        catalogID: '' // 目录
      },
      // 学科简单列表
      subjectList: [],
      // 二级目录简单列表
      catalogList: [],
      // 标签列表
      tagsList: [],
      // 试题类型列表
      questionList,
      // 难度列表
      difficultyList,
      // 方向列表
      directionList,
      // 审核状态列表
      chkStateList,
      // 发布状态列表
      publishTypeList,
      // 城市列表
      provinces,
      // 区域列表
      citys,
      // 录入人 -- 用户名列表
      creatorList: null,
      // 表格数据
      tableData: [],
      // 题目预览弹出层显示
      showDialogPreview: false,
      // 弹出层数据
      dialogData: {},
      // 单选正确答案标识
      right: 1,
      // 多选正确答案标识
      multipleRight: [1],
      // 展示视频答案
      isShowVideo: true,
      // 题目审核弹出层显示
      showDialogCheck: false,
      // 当前审核内容id
      checkId: '',
      // 审核状态
      chkState: '',
      // 审核意见内容
      chkRemarks: ' ',
      // 上架：1 ； 下架：0 ； 我认为是 上架 2 ； 下架 3 ,接口数据有问题 TODO
      putaway: 0
    }
  },
  beforeCreate: function () {
    // that = this
  },
  created () {
    this.search()
    this.getSubjectList()
    this.getCatalogList()
  },
  // 过滤器
  filters: {},
  // 计算属性
  computed: {
    // 学科
    getSubject () {
      return id => {
        return this.subjectList.find(key => key.value === id - 0) ? this.subjectList.find(key => key.value === id - 0).label : '未知'
      }
    },
    // 目录： id =》文字
    getCatalog () {
      // 计算属性接收参数必须这么写
      return id => {
        return this.catalogList.find(key => key.id === id) ? this.catalogList.find(key => key.id === id).directoryName : '未知'
      }
    },
    // 题型
    getQuestion () {
      return id => {
        return this.questionList.find(key => key.value === +id) ? this.questionList.find(key => key.value === +id).label : '未知'
      }
    },
    // 难度：
    getDifficulty () {
      return id => {
        return this.difficultyList.find(key => key.value === +id) ? this.difficultyList.find(key => key.value === +id).label : '未知'
      }
    },
    // 审核状态： id =》文字 -- 接口数据和静态数据不一致TODO
    getChkState () {
      return id => {
        // id = id === 0 ? 1 : id
        return this.chkStateList.find(key => key.value === +id + 1) ? this.chkStateList.find(key => key.value === +id + 1).label : '未知'
      }
    },
    // 发布状态： id =》文字 -- 发布状态数据和接口数据不一致TODO
    getPublishType () {
      return id => {
        id = id === 0 ? 1 : id
        return this.publishTypeList.find(key => key.value === +id) ? this.publishTypeList.find(key => key.value === +id).label : '未知'
      }
    }
  },
  methods: {
    // 获取学科列表
    async getSubjectList () {
      // 清空目录中的数据和标签中的数据
      this.formData.catalogID = ''
      this.formData.tags = ''
      const { data } = await subjectList()
      this.subjectList = data
    },
    // 获取目录列表
    async getCatalogList () {
      // 调整请求参数
      const queryObj = { ...this.queryObj(), pagesize: '', page: '' }
      const { data: { items } } = await catalogList(queryObj)
      this.catalogList = items
    },
    // 获取标签列表
    async getTagsList () {
      // 调整请求参数
      const queryObj = { ...this.queryObj(), pagesize: '', page: '' }
      const { data: { items } } = await tagsList(queryObj)
      this.tagsList = items
    },
    // 获取城市列表
    getProvinces () {
      this.formData.city = ''
      this.provinces = provinces()
    },
    // 获取区域列表
    getCitys () {
      this.citys = citys(this.formData.province)
    },
    // 获取录入人列表
    async getCreatorList () {
      const { data } = await creatorList()
      this.creatorList = data
    },

    // 标签页点击事件 -- 切换不同审核状态下的数据
    async handleClick (tab, event) {
      // 调接口，刷新表格数据
      let queryObj = {}
      this.chkState === '0' ? queryObj = this.queryObj() : queryObj = { ...this.queryObj(), chkState: this.chkState - 1 }
      // console.log(this.chkState)
      // if (this.chkState === '1') {
      //   // 待审核 中包含未知状态
      //   queryObj = { ...queryObj, chkState: 0 }
      // }
      this.search(queryObj)
    },

    // 点击搜索按钮事件
    async search (queryObj) {
      // 调整请求参数
      queryObj = { ...this.queryObj(), ...queryObj }
      const { data: { counts, pages, items } } = await getChoiceList(queryObj)
      this.tableData = items
      this.counts = counts
      this.pages = pages
    },

    // 封装调整请求参数的方法
    // 由于FormData数据多大，在此将FormData数据减轻，然后再调接口
    queryObj () {
      const queryObj = {}
      Object.keys(this.formData).forEach(key => {
        if (this.formData[key] !== '') {
          queryObj[key] = this.formData[key]
        }
      })
      return queryObj
    },

    // 点击取消按钮，重置表单数据
    async reset () {
      this.formData = {
        page: 1, // 当前页码
        pagesize: 2, // 页大小
        subjectID: '', // 学科
        difficulty: '', // 难度
        questionType: '', // 试题类型
        tags: '', // 标签名称
        province: '', // 城市
        city: '', // 区域
        keyword: '', // 关键字
        remarks: '', // 题目备注
        shortName: '', // 企业简称
        direction: '', // 方向
        creatorID: '', // 录入人
        catalogID: '' // 目录
      }
      await this.search()
    },

    // 预览按钮
    async preview (row) {
      // 调接口，拿到题目详情
      const { data } = await detail({ id: row.id })
      this.dialogData = data
      this.showDialogPreview = true
    },
    // 审核按钮
    async check (row) {
      // 记录当前id
      this.checkId = row.id
      this.showDialogCheck = true
    },
    // 审核确认按钮
    async CheckBtnOk () {
      // 调接口
      await choiceCheck({ id: this.checkId, chkState: this.chkState - 0, chkRemarks: this.chkRemarks })
      // 按照当前已选择的按钮重新获取表格数据
      this.CurrentChange()
      this.CheckBtnCancel()
    },
    // 审核取消按钮
    CheckBtnCancel () {
      // 数据恢复
      this.chkState = '2'
      this.chkRemarks = ' '
      this.showDialogCheck = false
    },

    // 题目上架、下架
    publish (row) {
      this.$confirm(`您确定${row.publishState === 2 ? '下架' : '上架'}这道题目吗？`, '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {
        // 判断当前应该上架还是下架
        if (row.publishState === 2) {
          // 下架
          this.putaway = 3
        } else {
          // 上架
          this.putaway = 2
        }
        // 调接口上架该题目
        await choicePublish({ id: row.id, publishState: this.putaway })
        this.$message.success(`${row.publishState === 2 ? '下架' : '上架'}成功`)
        // 重新调接口获取表格数据
        this.handleClick()
      }).catch(() => {
        this.$message.fail(`${row.publishState === 2 ? '下架' : '上架'}失败`)
      })
    },

    // 删除按钮
    async remove (row) {
      await remove({ id: row.id })
      // 重新调接口获取表格数据
      this.search()
    },

    // 分页组件方法
    CurrentChange () {
      // 调接口，刷新表格数据
      let queryObj = {}
      // 审核数据有问题TODO
      this.chkState === '0' ? queryObj = this.queryObj() : queryObj = { ...this.queryObj(), chkState: this.chkState - 1, page: this.formData.page, pagesize: this.formData.pagesize }
      this.search(queryObj)
    },
    SizeChange () {
      this.CurrentChange()
    }
  }
}

</script>

<style scoped>
.container {
  padding: 10px;
}
.showVideo {
  display: none;
}
.ellipsisStyle {
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
</style>
